package com.wondersgroup.service.impl;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wondersgroup.entity.Company;
import com.wondersgroup.entity.CompanyVo;
import com.wondersgroup.entity.Person;
import com.wondersgroup.mapper.CompanyMapper;
import com.wondersgroup.mapper.PersonMapper;
import com.wondersgroup.service.CompanyService;
import com.wondersgroup.util.RsaUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Service
@Transactional
public class CompanyServiceImpl implements CompanyService {


  @Autowired
  private CompanyMapper companyMapper;

  @Autowired
  private DefaultKaptcha defaultKaptcha;

  @Autowired
  private PersonMapper personMapper;


  public static Map<String, Object> yzmMap = new HashMap<>();

  @Override
  public Company getCompanyById(String id) {
    return companyMapper.getCompanyById(id);
  }

  @Override
  public Map<String, Object> login(String sjh, String zjhm, String yzm, String openId) throws Exception{
    Map<String, Object> map = new HashMap<>();
    //首先校验验证码
    Object obj = yzmMap.get(yzm);
    if (obj == null) {
      map.put("code", 500);
      map.put("msg", "验证码错误！");
      return map;
    }
    //验证是否注册
    Company temp = companyMapper.getCompanyById(openId);
    if (temp == null) {
      map.put("code", 501);
      map.put("msg", "未注册！跳转到注册页面");
      return map;
    }
    Company co = companyMapper.isRegister(sjh, zjhm);
    if (co == null) {
      map.put("code", 500);
      map.put("msg", "手机号或证件号码错误！");
      return map;
    } else {
      CompanyVo vo = getCompanyVo(co);
      vo = getTmData(vo);
      vo = getRsaData(vo);
      map.put("code", 200);
      map.put("company", vo);
      return map;
    }
  }


  @Override
  public Company isRegister(String sjh, String zjhm) {
    return companyMapper.isRegister(sjh, zjhm);
  }

  @Override
  public String getDwmc(String sjh, String zjhm, String yxbz) throws Exception {
    return companyMapper.getDwmc(sjh, zjhm, yxbz);
  }

  @Override
  public CompanyVo register(Company company) throws Exception {
    //注册
    companyMapper.register(company);
    // 向person表里边插入一条数据
    addPerson(company);
    Company co = companyMapper.getCompanyById(company.getId());
    CompanyVo vo = getCompanyVo(co);
    vo = getTmData(vo); // 脱敏
    vo = getRsaData(vo); // 加密
    return vo;
  }

  //person表里新增一条数据
  private void addPerson(Company company) throws Exception{
    Person person = new Person();
    person.setId(UUID.randomUUID().toString().replace("-",""));
    person.setOpenId(company.getId());
    person.setXm(company.getSqrxm());
    person.setZjlx(company.getSqrzjlx());
    person.setZjhm(company.getSqrzjhm());
    person.setSjhm(company.getSqrsjh());
    person.setZcsj(company.getSqsj());
    person.setXgsj(company.getXgsj());
    person.setYxbz(company.getYxbz());
    personMapper.addPerson(person);
  }

  @Override
  public List<Company> getAllCompanys() {
    return companyMapper.getAllCompanys();
  }

  @Override
  public String createPicVerificationCode(String param, HttpServletRequest request) {
    if (StringUtils.isNotBlank(param)) {
      byte[] captchaChallengeAsJpeg;
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      try {
        String verificationCodeText = defaultKaptcha.createText();
        //加入到缓存里方便后面验证
        yzmMap.clear();
        yzmMap.put(verificationCodeText, verificationCodeText);
        System.out.println("code..." + verificationCodeText);
        BufferedImage image = defaultKaptcha.createImage(verificationCodeText);
        ImageIO.write(image, "jpg", outputStream);
        captchaChallengeAsJpeg = outputStream.toByteArray();
        return Base64.getEncoder().encodeToString(captchaChallengeAsJpeg);
      } catch (Exception e) {
        System.out.println(("生成图片验证码异常" + e));
        e.printStackTrace();
      } finally {
        try {
          outputStream.close();
        } catch (IOException e) {
          System.out.println(("生成图片验证码结束，关闭ByteArrayOutputStream资源失败" + e));
          e.printStackTrace();
        }
      }
    }
    return null;
  }


  //转换
  private CompanyVo getCompanyVo(Company company) {
    CompanyVo result = new CompanyVo();
    if (company != null) {
      result.setId(company.getId());
      result.setDwmc(company.getDwmc());
      result.setDwdz(company.getDwdz());
      result.setSqrxm(company.getSqrxm());
      result.setSqrzjlx(company.getSqrzjlx());
      result.setSqrzjhm(company.getSqrzjhm());
      result.setSqrsjh(company.getSqrsjh());
      result.setSqsj(company.getSqsj());
      result.setXgsj(company.getXgsj());
      result.setYxbz(company.getYxbz());
      // 子类属性值
      result.setRsaSqrxm(company.getSqrxm());
      result.setRsaSqrsjh(company.getSqrsjh());
      result.setRsaSqrzjhm(company.getSqrzjhm());
    }
    return result;
  }


  // 脱敏方法
  private CompanyVo getTmData(CompanyVo vo) {
    //手机号转换
    if (vo.getSqrsjh() != null && !vo.getSqrsjh().equals("")) {
      String phoneNumber = vo.getSqrsjh().substring(0, 3) + "****" + vo.getSqrsjh().substring(7, vo.getSqrsjh().length());
      vo.setSqrsjh(phoneNumber); // 脱敏
    }
    //姓名转换
    if (vo.getSqrxm() != null && !vo.getSqrxm().equals("")) {
      String xm = "*" + vo.getSqrxm().substring(1, vo.getSqrxm().length());
      vo.setSqrxm(xm);
    }
    // 身份证号转换
    if (vo.getSqrzjhm() != null && !vo.getSqrzjhm().equals("")) {
      String zjhm = vo.getSqrzjhm().substring(0, 3) + "***********" + vo.getSqrzjhm().substring(14, vo.getSqrzjhm().length());
      vo.setSqrzjhm(zjhm);
    }
    return vo;
  }


  // 加密方法
  private CompanyVo getRsaData(CompanyVo vo) throws Exception {
    if (vo.getRsaSqrxm() != null && !vo.getRsaSqrxm().equals("")) {
      //先转码
      vo.setRsaSqrxm(URLEncoder.encode(vo.getRsaSqrxm(), "UTF-8" ));
      vo.setRsaSqrxm(RsaUtil.getEncData(vo.getRsaSqrxm()));
    }
    if (vo.getRsaSqrsjh() != null && !vo.getRsaSqrsjh().equals("")) {
      vo.setRsaSqrsjh(RsaUtil.getEncData(vo.getRsaSqrsjh())); //加密
    }
    if (vo.getRsaSqrzjhm() != null && !vo.getRsaSqrzjhm().equals("")) {
      vo.setRsaSqrzjhm(RsaUtil.getEncData(vo.getRsaSqrzjhm()));
    }
    return vo;
  }
}
